package priv.cwr.springboot.demo.configuration;

import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import priv.cwr.springboot.demo.component.Errors;
import priv.cwr.springboot.demo.exception.ApiException;
import priv.cwr.springboot.demo.model.vo.base.Result;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

/**
 * User: R
 * Date: 2018/8/29
 * Time: 18:00
 * Created with IntelliJ IDEA.
 * controller的全局错误处理handler
 */
@ControllerAdvice
@Log4j2
public class GlobalExceptionHandler extends RuntimeException {
    private final Errors errors;

    public GlobalExceptionHandler(Errors errors) {
        this.errors = errors;
    }

    /**
     * 处理spring boot + hibernate validators的表单验证错误
     *
     * @param cve ConstraintViolationException
     * @return error
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    ResponseEntity<?> handleConstraintViolationException(ConstraintViolationException cve) {
//         Result r = new Result(errors, Global.Errors.VALID_ERROR, HttpStatus.BAD_REQUEST.value());
//         final Result result = setParam(r, path, cve.getClass().getName(), request);
        final Result result = new Result(errors, Global.Errors.VALID_ERROR, HttpStatus.BAD_REQUEST.value());
        Set<ConstraintViolation<?>> cves = cve.getConstraintViolations();
        boolean fit = cves.stream().anyMatch(constraintViolation -> {
            result.setMessage(constraintViolation.getMessage());
            return true;
        });
        // 如果没有发现配置的错误信息
        if (!fit) {
            result.setMessage(Global.Errors.VALID_ERROR.getMessage());
        }
        //方便前端处理，所有的response status都为ok 200
        // return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 处理通用错误
     *
     * @param request http 请求
     * @param e       exception
     * @return error
     */
    @ExceptionHandler(Exception.class)
    ResponseEntity<?> handleControllerException(HttpServletRequest request, Throwable e) {
        String path = request.getServletPath();
        HttpStatus status = getStatus(request);
        if (e instanceof ApiException) { //自定义异常
            Result result = ((ApiException) e).getResult();
            result = setParam(result, path, e.getClass().getName(), request);
            // ApiException exception = (ApiException) e;
            log.error(e.getMessage(), e);
            //方便前端处理，所有的response status都为ok 200
            // return new ResponseEntity<>(result, HttpStatus.valueOf(exception.getResult().getStatus()));
            return new ResponseEntity<>(result, HttpStatus.OK);
        }
        return null;
    }

    private Result setParam(Result result, String path, String exception, HttpServletRequest request) {
        result.setPath(path);
        result.setException(exception);
        return result;
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }
}
